/**
* 
* 
* 
* 
**/
(function() {
	var platformWidth = S.ui.properties.platformWidth;
	var GLOBAL_SESSID;
	S.ui.content = Array();
	S.ui.tabsIndexes = Array();
	
	S.ui.initInterface = function(_args) {
		S.Xhr({
			url: "http://platform.electiontools.org:80/drupal6/?q=api/views/appcelerator_interface.json",
			onerror: function(e){
				if (!_args.force) {
					S.auth.createSession({force:true});
				} else {
			        Ti.API.debug(e.error);
			        alert(e.error);
				}
			},
			onload: function(){
				S.json = JSON.parse(this.responseText);

				S.ui.content.push(new Array("_views")); // Index 0
				S.ui.content.push(new Array("_ads")); // Index 1
				
				for (i = 0; i < S.json.length; i++) {
					
					var param_id = S.json[i]['ui_id'];
					var param_type = S.json[i]['node_data_field_app_id_field_type_value'];
					var	param_location = S.json[i]['node_data_field_app_id_field_ui_location_value'];
					var param_href = S.json[i]['node_data_field_app_id_field_ui_href_value'];
					var param_body = S.json[i]['body'];
					var param_weight = S.json[i]['node_data_field_app_id_field_ui_weight_value'];
					var param_template = S.json[i]['ui_template'];								
					var param_init = S.json[i]['init_function'];
		
					// Generate ui parameters array
					switch (param_type) {
						case 'view':
							// Check if the page is local and requires ajax
							// For now same calls are generated for all types of locations
							var page = (param_location == "local") ? {id:param_id, weight:param_weight, html:param_body, template:param_template, init:param_init} : {id:param_id, url:param_href, method:'GET'};
							S.ui.content[0].push(page);
						break;
						case 'ads':
							S.ui.content[1].push(param_body);
						break;
						case 'loader':
							S.ui.content[0].push({id:param_id, weight:-1});
						break;
					}
				}

				if (S.ui.content.length > 0) {
					
					//Ti.App.fireEvent("app:isLoading");
					S.ui.createApplicationWindow();
										
				}
			},
			method: "GET",
			params: {
		    	'contentType': 'application/x-www-form-urlencoded',
				'username': S.auth.user,
				'password': S.auth.password,
				'sessid': S.auth.sessid
			}
		});
	};
	
	//create the main application window
	S.ui.createApplicationWindow = function(_args) {

		Ti.API.debug("CONTENT: " + JSON.stringify(S.ui.content));
		
		headerView = Ti.UI.createView(S.combine($$.headerView)),
		tabView = Titanium.UI.createScrollView(S.combine({id:'tabsContainer',scrollType:'HORIZONTAL'}, $$.tabView)),
		tabs = [],
		tabSize = S.ui.layout.tabSize;

		// Creating the header
		var headerLbl = Ti.UI.createLabel(S.combine($$.headerLabel));
		headerView.add(headerLbl);


		/* Navigation tabs */
		
		/* Helper functions */
		//create clickable tab images
		function createTab(title,index,_on) {
			var view = Ti.UI.createView({width:tabSize}),
			    label = Ti.UI.createLabel({text:title,textAlign:"center"}),
				dimension = 40;
			
			var tabIndex = index;
			view.on = _on||false; //ivar for 'on' state
			
			//assemble view
			view.add(label);
			
			view.addEventListener('click',function(){selectIndex(tabIndex)});
			view.addEventListener('click', function(){Ti.App.fireEvent("app:changeTitle",{title: label.text})});
			
			//'instance' method
			view.toggle = function() {
				view.on = !view.on;
				//label.text = label.text[view.on ? "toUpperCase" : "toLowerCase"]();
			};
	
			return view;
		}
		
		//toggle view state of application to the relevant tab
		function selectIndex(_idx) {
			Ti.API.debug("Current Index: " + _idx);
			for (var i = 0, l = tabs.length; i<l; i++) {
				//select the tab and move the tab 'cursor'
				if (_idx === i) {
					//if the tab is already selected, do nothing
					if (!tabs[i].on) {
						//animate the tab
						tab.animate({
							duration:0,
							left:tabSize*i,
							bottom:0
						},function(idx) { //use closure to retain value of i in idx
							return function() {
								if (!tabs[idx].on) {
									tabs[idx].toggle();
								}
							};
						}(i));
						
						//set the current film strip index
						appFilmStrip.fireEvent('changeIndex',{idx:i});
					}
				}
				else if (tabs[i].on && (_idx !== i)) {
					tabs[i].toggle();
				}
			}
		}
		
		// Populates the views
		function populateViews() {
			var views = [];
			S.ui.createView = Array();
			for (t = 1; t < S.ui.content[0].length; t++) {
				// Including the view js files
				Ti.include("/struct/views/" + S.ui.content[0][t]['id'] + ".js");
				views.push(S.ui.createView(S.ui.content[0][t]['id']));
				//Ti.API.debug("Loop t: " + JSON.stringify(S.ui.tabsIndexes));
			}
			return views;
		}
		/* End Helper functions */
		
		
		/* Create tabs */
		
		//create the 'tab' view, which we will animate back and forth along the tab bar
		var tab = Ti.UI.createView(S.combine($$.tabItem));
		tab.add(Ti.UI.createView());
		tabView.add(tab);
		
		// Populates the tabs based on the cms
		var selected = false;
		var tabItem;
		for (t = 1; t < S.ui.content[0].length; t++) {
			S.ui.tabsIndexes.push(t);
			//Ti.API.debug("Loop t: " + JSON.stringify(S.ui.tabsIndexes));
			selected = ( t == 1 ) ? true : false;
			tabItem = createTab(
				S.ui.content[0][t]['id'],
				t-1,
				selected
			);
			tabs.push(tabItem);
		}
		
		//add tabs to layout
		for (var i = 0, l = tabs.length; i<l; i++) {
			tabs[i].left = tabSize*i;
			tabView.add(tabs[i]);
		}

		
		
		//Add the main app 'filmstrip'	
		var appFilmStrip = S.ui.createFilmStripView({
			/*views: [
				S.ui.createAboutView(),
				S.ui.createNewsView(),
				S.ui.createGalleryView()
			]*/
			views: populateViews()
		});



		/* LISTENERS */
			
		//App app-level event listener to change tabs
		Ti.App.addEventListener('app:change.tab', function(e) {
			selectIndex(e.tabIndex);
		});
		
		// Scrolling by blocks for tabs
		tabView.addEventListener("scroll",function(e){
		    if (tabView.timeout) { 
		    	clearTimeout(tabView.timeout); 
		    }   
		    tabView.timeout = setTimeout(function() { 
		        var val = e.x / tabSize;
		        var offsetting = Math.round(val) * tabSize;
		        tabView.scrollTo(offsetting,0);
		    },100); 
		});	

		// Change the header title 
		Ti.App.addEventListener("app:changeTitle",function(e){
			headerLbl.text = e.title;
		});


		// Hiding header whenever the content is scrolled
		Ti.App.addEventListener("app:headerHide",function(e){
			// Animation for header
			var headerHideAnimation = Titanium.UI.createAnimation();
			headerHideAnimation.duration = 350;
			headerHideAnimation.opacity = 0;
			headerHideAnimation.top = (S.ui.layout.tabSize/2)*(-1);
			headerView.animate(headerHideAnimation);
		});
		
		// Hiding tabs whenever the content is scrolled
		Ti.App.addEventListener("app:tabsHide",function(e){
	    	S.ui.tabsHidden = true;
			// Animation for tabs
			var tabsHideAnimation = Titanium.UI.createAnimation();
			tabsHideAnimation.duration = 150;
			tabsHideAnimation.opacity = 0;
			tabsHideAnimation.bottom = S.ui.layout.tabSize*(-1);
			tabView.animate(tabsHideAnimation);
		});

		// Showing header whenever the content reached it's limits
		Ti.App.addEventListener("app:headerShow",function(e){
			var headerShowAnimation = Titanium.UI.createAnimation();
			headerShowAnimation.duration = 150;
			headerShowAnimation.opacity = 1;
			headerShowAnimation.top = 0;
			headerView.animate(headerShowAnimation);
		});
		
		// Showing tabs whenever the content reached it's limits
		Ti.App.addEventListener("app:tabsShow",function(e){
			S.ui.tabsHidden = false;
			//Ti.App.fireEvent("app:msg",{msg: "tabs show event fired"});
			var tabsShowAnimation = Titanium.UI.createAnimation();
			tabsShowAnimation.duration = 350;
			tabsShowAnimation.opacity = 1;
			tabsShowAnimation.bottom = 0;
			tabView.animate(tabsShowAnimation);
		});
		
		// add msg view
		var msgview = Ti.UI.createView({opacity:0,zIndex:10,width:platformWidth-100,left:50,top:230,height:100}),
			msglabel = Ti.UI.createLabel($$.Label);
		msgview.add(msglabel);
		
		Ti.App.addEventListener("app:msg",function(e){
			//Ti.API.log(e);
			msglabel.text = e.msg;
			msgview.backgroundColor = e.error ? "red" : "white";
			msgview.opacity = 1;
			msgview.animate({
				opacity: 0,
				duration: 1500
			});
		});
		
		//assemble main app window
		S.mainWin.add(headerView);
		S.mainWin.add(msgview);
		S.mainWin.add(appFilmStrip);
		S.mainWin.add(tabView);
		
		// Set default view
		appFilmStrip.fireEvent('changeIndex',{idx:0});

		// Set default title
		Ti.App.fireEvent("app:changeTitle",{title: "about"});	
				
		// Hide Loading indicator
		Ti.App.fireEvent("app:doneLoading");
		
		//return mainWin;
	};
})();